/*
@STI LICENSE
(C) 2006-2008 Universit�t Innsbruck.

This file is part of myOntology.

myOntologyis free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

myOntologyis distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with myOntology.  If not, see <http://www.gnu.org/licenses/>.

@STI LICENSE */
package controller.elementMapper;

import java.util.ArrayList;

import model.Vocabulary;

import org.apache.log4j.Logger;
import org.openrdf.model.URI;
import org.openrdf.model.impl.URIImpl;
import org.openrdf.query.QueryLanguage;
import org.openrdf.query.TupleQuery;
import org.openrdf.query.TupleQueryResult;
import org.openrdf.repository.RepositoryConnection;

import controller.sesameDataConnector.AbstractDataConnector;


public class FreezepointMapper {

	public static Logger logger = Logger.getLogger(FreezepointMapper.class);
	
	public static ArrayList<URI> selectAllFreecepoints( URI ontologyUri ) {
		
		ArrayList<URI> ret = null;

		// TODO
		// Order by is yet not supported. So this is not efficiently salved
		ret = AbstractDataConnector.selectObjects( ontologyUri, Vocabulary.HASFREEZEPOINT );
		
		return ret;	
	}

	public static URI selectLastFreecePoint( URI ontologyUri ) {

		// TODO
		// Order by is yet not supported. So this is not efficiently salved
		
		URI ret = null;

		try {
			RepositoryConnection con = AbstractDataConnector.getConnection();	
			
			try {
				String query = 
					"SELECT DISTINCT x FROM {<" + ontologyUri.stringValue() + ">} <"+ Vocabulary.HASFREEZEPOINT +"> {x}";
				


				TupleQuery tupleQuery = con.prepareTupleQuery(QueryLanguage.SERQL, query);
				TupleQueryResult result = tupleQuery.evaluate();

				try {
					
					String tmp = "";
					String actual = "";
					
					while (result.hasNext()) {
						tmp = result.next().getValue("x").stringValue();
						
						if( actual.compareTo( tmp ) < 0 ) {
							actual = tmp;
						}
					}
					
					if( !actual.equals(""))
						ret = new URIImpl( actual );
					
					
				} finally {
					result.close();
				}
			} finally {
				con.close();
			}
			
		} catch (Exception e) {
			logger.error("Error while selecting ",e);
			return null;
		}
		
		return ret;	
	}
	
}
